package org.jeecg.modules.wflow.controller;

//import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.config.shiro.JwtToken;
import org.jeecg.modules.wflow.bean.vo.UserLoginVo;
import org.jeecg.modules.wflow.service.AuthService;
import org.jeecg.modules.wflow.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : willian fu
 * @date : 2022/8/15
 */
@RestController
@RequestMapping("wflow/sys/auth")
public class AuthController {

    @Autowired
    ISysBaseAPI sysBaseAPI;

    @Autowired
    private AuthService authService;

    /**
     * 获取登录验证码，暂未使用
     * @param request 请求
     * @param response 响应
     * @throws IOException
     */
    @GetMapping("login/code")
    public void getLoginCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        authService.getLoginCode(request, response);
    }

    /**
     * 用户登录，暂未使用, 不用这个接口进行登录。不用这个接口登录。
     * @param request 请求
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @return 登录结果
     */
    @GetMapping("login")
    public Object userLogin(HttpServletRequest request,
                            @RequestParam String username,
                            @RequestParam String password,
                            @RequestParam String code) {
        UserLoginVo loginVo = authService.userLogin(request, username, password, code);
        return R.ok(loginVo);
    }

    /**
     * 忽略账号密码快速登录进行用户切换
     * @return 登录用户的信息
     */
//    @GetMapping("login/ignore/{userId}")
//    public Object userLoginIgnore(@PathVariable String userId) {
//        UserLoginVo loginVo = authService.userLoginIgnore(userId);
//        return R.ok(loginVo);
//    }

    @ApiOperation(value = "getCurrentUser", notes = "根据已知token，获取当前登录用户信息")
    @GetMapping(value = "/getCurrentUser")
    public Object getCurrentUser(HttpServletRequest request,HttpServletResponse response){
        String token = request.getParameter("token");
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        SecurityUtils.getSubject().login(jwtToken);

        String username = JwtUtil.getUsername(token);
        LoginUser loginUser = sysBaseAPI.getUserByName(username);
        if(loginUser!=null) {
            UserLoginVo loginVo =new UserLoginVo();
            loginVo.setUserId(loginUser.getId());
            loginVo.setUserName(loginUser.getRealname());
            loginVo.setAlisa(loginUser.getUsername());
            loginVo.setXAccessToken(token);
            loginVo.setToken(token);
            loginVo.setAvatar(loginUser.getAvatar());
            return R.ok(loginVo);

//            UserLoginVo loginVo = authService.userLoginIgnore(sysUser.getId());
//            loginVo.setXAccessToken(token);
            //return R.ok(loginVo);
        }
        return null;
    }


    /**
     * 切换用户模拟登录
     * @param uid
     * @return
     */
    @PostMapping("/switchUserLogin")
    public Object switchUserLogin(@RequestParam("uid") String uid){
        LoginUser loginUser = sysBaseAPI.getUserById(uid);
        System.out.println("切换用户模拟登录------------------------");
        System.out.println(JSON.toJSONString(loginUser));
        System.out.println("切换用户模拟登录------------------------");
        if(loginUser!=null) {
            String token = getTemporaryToken(loginUser);
            System.out.println("获取临时令牌，模拟登录："+token);
            UserLoginVo loginVo =new UserLoginVo();
            loginVo.setUserId(loginUser.getId());
            loginVo.setUserName(loginUser.getRealname());
            loginVo.setAlisa(loginUser.getUsername());
            loginVo.setXAccessToken(token);
            loginVo.setToken(token);
            loginVo.setAvatar(loginUser.getAvatar());
            return R.ok(loginVo);
        }
        return null;
    }

    /**
     * 获取临时令牌
     *
     * 模拟登陆接口，获取模拟 Token
     * @return
     */
    private String getTemporaryToken(LoginUser loginUser) {
        RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
        String token = JwtUtil.sign(loginUser.getUsername(), loginUser.getPassword());
        // 设置Token缓存有效时间为 60 分钟
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, 60 * 60 * 1000);
        return token;
    }

//    @ApiOperation(value = "getCurrentUser2", notes = "直接获取当前登录用户信息2")
//    @GetMapping(value = "/getCurrentUser2")
//    public LoginUser getCurrentUser2(){
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        return sysUser;
//    }
//
//    @ApiOperation(value = "getCurrentUser3", notes = "直接获取当前登录用户信息2")
//    @GetMapping(value = "/getCurrentUser3")
//    public LoginUser getCurrentUser3(HttpServletRequest request,HttpServletResponse response){
//        String token = request.getHeader("X-Access-Token");
//        String username = JwtUtil.getUsername(token);
//        LoginUser sysUser = sysBaseAPI.getUserByName(username);
//        return sysUser;
//    }
//
//    @ApiOperation(value = "getTenantId", notes = "获取当前租户信息")
//    @GetMapping(value = "/getTenantId")
//    public String getTenantId(HttpServletRequest request){
//        String tenantId = request.getHeader("tenant-id");
//        return tenantId;
//    }
//    @ApiOperation(value = "getToken", notes = "获取当前token认证信息")
//    @GetMapping(value = "/getToken")
//    public String getToken(HttpServletRequest request){
//        String token = request.getHeader("X-Access-Token");
//        return token;
//    }
}
